package com.item.task;

import com.item.mapper.ComputerMapper;
import com.item.utils.RedisUtil;
import com.item.utils.ThreadLocalUtil;
import jakarta.annotation.security.RunAs;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;

/**
 * 电脑上机后实时扣费的 定时任务
 * @author likaiping
 * @createTime 2024/5/14 15:12
 */
@Component
@AllArgsConstructor
@NoArgsConstructor
public class ComputerBalanceTask implements Runnable {
    private String username;
    private BigDecimal simplePrice;
    private ComputerMapper computerMapper;
    private RedisUtil redisUtil;
    //具体的任务操作
    @Override
    public void run() {
        try {
            //单价除以60分钟，即为每分钟的花费 做除法并保留2位小数
            BigDecimal balanceForSecond = simplePrice.divide(BigDecimal.valueOf(60),2, RoundingMode.HALF_UP);
            System.out.println("定时任务中每秒的消费："+balanceForSecond);
            computerMapper.updateBalanceByUsername(balanceForSecond,username);

            //在线程变量中更新用户花费的金额
            String pointInRedis = (String) redisUtil.get("balanceForPoints_" + username);
            BigDecimal point = pointInRedis == null? BigDecimal.valueOf(0.00) : BigDecimal.valueOf(Double.parseDouble(pointInRedis));
            String points = String.valueOf(point.add(balanceForSecond));
            redisUtil.set("balanceForPoints_"+username,points);
//            ThreadLocalUtil.set(pointMap);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public BigDecimal getSimplePrice() {
        return simplePrice;
    }

    public void setSimplePrice(BigDecimal simplePrice) {
        this.simplePrice = simplePrice;
    }

    public ComputerMapper getComputerMapper() {
        return computerMapper;
    }

    public void setComputerMapper(ComputerMapper computerMapper) {
        this.computerMapper = computerMapper;
    }

    public RedisUtil getRedisUtil() {
        return redisUtil;
    }

    public void setRedisUtil(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    //    public ComputerBalanceTask(String username, BigDecimal simplePrice) {
//        this.username = username;
//        this.simplePrice = simplePrice;
//    }
//    public ComputerBalanceTask() {
//    }
}
